package com.ca.ridersclubapplication.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.ca.ridersclubapplication.AccountActivity;
import com.ca.ridersclubapplication.ClubActivity;
import com.ca.ridersclubapplication.PaperActivity;
import com.ca.ridersclubapplication.R;
import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.data.entity.BooleanEntity;
import com.ca.ridersclubapplication.data.entity.Handleable;
import com.ca.ridersclubapplication.request.AfterExecutor;
import com.ca.ridersclubapplication.request.PaperRequester;
import com.ca.ridersclubapplication.request.dto.PaperCardDto;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.util.ActivityStarter;
import com.ca.ridersclubapplication.util.PaperUtils;
import com.ca.ridersclubapplication.view.CallbackView;
import com.ca.ridersclubapplication.view.button.IconButton;
import com.ca.ridersclubapplication.view.card.PaperCard;
import com.ca.ridersclubapplication.view.card.PostCommentCard;
import com.ca.ridersclubapplication.view.header.MainHeaderView;
import com.ea.ui.core.basic.EATextField;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class PaperAdapter extends RecyclerView.Adapter<PaperAdapter.PaperHolder> {

    private final Activity activity;
    private List<PaperCardDto> list;

    public PaperAdapter(Activity activity, List<PaperCardDto> list) {
        this.list = list == null ? new ArrayList<>() : list;
        this.activity = activity;
    }

    @NonNull
    @Override
    public PaperHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.paper_item_layout, parent, false);
        return new PaperHolder(view);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onBindViewHolder(@NonNull PaperHolder holder, int position) {
        holder.mainHeaderView.setVisibility(View.GONE);
        holder.paperCard.setVisibility(View.VISIBLE);

        PaperCardDto dto = list.get(position);
        holder.paperCard.setPaper(dto);
        holder.mainHeaderView.setActivity(activity);
        holder.paperCard.clubNameView.setText(dto.getClubName());
        //  解析内容，获取文章图片路径数组
        String[] array = PaperUtils.parsePaperImageUrlArray(dto.getContent());
        if (activity != null) {
            holder.paperCard.imageView.setOnClickListener(v -> {
                ActivityStarter.startImageActivity(
                        activity,
                        array,
                        0);
            });

            holder.paperCard.headerView.setOnClickListener(v -> {
                Intent intent = new Intent(activity, AccountActivity.class);
                intent.putExtra("accountId", dto.getAuthorId());
                activity.startActivity(intent);
            });

            holder.paperCard.clubNameView.setOnClickListener(v -> {
                Intent intent = new Intent(activity, ClubActivity.class);
                intent.putExtra("clubId", dto.getClubId());
                activity.startActivity(intent);
            });


            //  文章删除回调视图
            DataHandler.putView("PaperDelete:" + dto.getId(), new CallbackView() {
                @SuppressLint("NotifyDataSetChanged")
                @Override
                public void update() {
                    Handleable data = DataHandler.getData("PaperDelete:" + dto.getId());
                    if (data instanceof BooleanEntity) {
                        BooleanEntity isDelete = (BooleanEntity) data;
                        if (isDelete.getValue()) {
                            //  删除该文章
                            list.remove(dto);
                            notifyDataSetChanged();
                        }
                    }
                }
            });


            final IconButton supportButton = holder.paperCard.supportButton;
            final IconButton commentButton = holder.paperCard.commentButton;
            //  请求文章点赞数
            PaperRequester.getSupportCount(activity, dto.getId(), new AfterExecutor<Long>() {
                @Override
                public void execute(Result<Long> result) {
                    if (result.isSuccess()) {
                        supportButton.setValue(result.getData());
                    }
                }
            });

            //  请求文章评论数
            PaperRequester.getCommentCount(activity, dto.getId(), new AfterExecutor<Long>() {
                @Override
                public void execute(Result<Long> result) {
                    if (result.isSuccess()) {
                        commentButton.setValue(result.getData());
                    }
                }
            });

            //  请求文章是否点赞
            if (DataHandler.isLogin(activity)) {
                PaperRequester.isSupport(activity, dto.getId(), new AfterExecutor<Boolean>() {
                    @Override
                    public void execute(Result<Boolean> result) {
                        Boolean isSupport = result.getData();
                        //  已点赞
                        supportButton.setActive(
                                result.isSuccess()
                                        && isSupport != null
                                        && isSupport);
                    }
                });
            }

            //  点赞按钮事件
            supportButton.setOnClickListener(v -> {

                supportButton.setEnabled(false);

                if (!supportButton.isActive()) {
                    //  如果没有点赞，则发起点赞请求
                    PaperRequester.addSupport(activity, dto.getId(), new AfterExecutor<String>() {
                        @Override
                        public void execute(Result<String> result) {
                            supportButton.setActive(true);
                            if (result.isSuccess()) {
                                //  点赞成功，改变按钮样式，数据 + 1
                                long count = supportButton.getValue() + 1;
                                supportButton.setValue(count);
                                dto.setSupportCount(count);
                            }
                            else {
                                Toast.makeText(activity, result.getMessage(), Toast.LENGTH_SHORT).show();
                            }

                            supportButton.setEnabled(true);
                        }
                    });
                }
                else {
                    //  发起取消点赞请求
                    PaperRequester.deleteSupport(activity, dto.getId(), new AfterExecutor<String>() {
                        @Override
                        public void execute(Result<String> result) {
                            supportButton.setActive(false);
                            if (result.isSuccess()) {
                                //  点赞成功，改变按钮样式，数据 - 1
                                long count = supportButton.getValue() - 1;
                                supportButton.setValue(count);
                                dto.setSupportCount(count);
                            }
                            else {
                                Toast.makeText(activity, result.getMessage(), Toast.LENGTH_SHORT).show();
                            }

                            supportButton.setEnabled(true);
                        }
                    });
                }
            });

            //  评论按钮事件
            commentButton.setOnClickListener(v -> {

                //  弹出快捷评论对话框
                @SuppressLint("InflateParams")
                View view = LayoutInflater.from(activity).inflate(R.layout.quick_comment_dialog_layout, null);
                Dialog dialog = new Dialog(activity);
                dialog.setContentView(view);
                dialog.show();

                PostCommentCard pcc = view.findViewById(R.id.card_post);
                TextView titleView = pcc.titleView;
                EATextField input = pcc.input;
                Button submitButton = pcc.submitButton;
                titleView.setText(dto.getTitle());
                submitButton.setOnClickListener(v1 -> {
                    String content = Objects.requireNonNull(input.getText()).toString();
                    if (!content.trim().isEmpty()) {

                        submitButton.setEnabled(false);

                        //  发送请求
                        PaperRequester.addComment(activity, dto.getId(), content, new AfterExecutor<String>() {
                            @Override
                            public void execute(Result<String> result) {
                                if (result.isSuccess()) {
                                    //  发送成功
                                    dialog.dismiss();
                                    //  数据 + 1
                                    long count = commentButton.getValue() + 1;
                                    commentButton.setValue(count);
                                    dto.setCommentCount(count);
                                }
                                else {
                                    Toast.makeText(activity, result.getMessage(), Toast.LENGTH_SHORT).show();
                                }

                                submitButton.setEnabled(true);
                            }
                        });
                    }
                    else {
                        Toast.makeText(activity, "请输入评论的内容", Toast.LENGTH_SHORT).show();
                    }
                });
            });

            //  文章点击事件
            holder.paperCard.setOnClickListener(v -> {
                Intent intent = new Intent(activity, PaperActivity.class);
                intent.putExtra("paperId", dto.getId());
                activity.startActivity(intent);;
            });
        }
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @SuppressLint("NotifyDataSetChanged")
    public void setList(List<PaperCardDto> list) {

        if (list == null) {
            list = new ArrayList<>();
        }

        if (!this.list.equals(list)) {
            this.list = list;
            notifyDataSetChanged();
        }
    }

    /**
     * 追加新的数据
     * @param list 传入的列表为新的数据列表
     */
    public void appendList(List<PaperCardDto> list) {

        if (list == null) {
            return;
        }

        int startPosition = getItemCount();

        //  添加数据
        for (PaperCardDto dto : list) {
            if (!this.list.contains(dto)) {
                this.list.add(dto);
            }
        }

        //  如果没有新的数据添加，弹出提示
        if (startPosition == this.list.size()) {
            Toast.makeText(activity, "暂时没有更多数据了", Toast.LENGTH_SHORT).show();
        }

        notifyItemRangeInserted(startPosition, this.list.size() - startPosition);
    }


    public void appendPaperToTop(PaperCardDto dto) {
        list.add(0, dto);
        notifyItemInserted(0);
    }


    public static class PaperHolder extends RecyclerView.ViewHolder {

        public MainHeaderView mainHeaderView;
        public PaperCard paperCard;

        public PaperHolder(@NonNull View itemView) {
            super(itemView);
            mainHeaderView = itemView.findViewById(R.id.mainHeader);
            paperCard = itemView.findViewById(R.id.card_paper);
        }
    }
}
